package com.sergio.compress.model.channelWapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.databind.CBORMapper;
import com.fasterxml.jackson.dataformat.ion.IonObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.sergio.compress.model.base.ChannelWrapper;
import lombok.Data;
import org.springframework.util.StopWatch;

import java.util.List;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/15 20:02
 */
@Data
public abstract class JacksonIONWrapper<T> extends ChannelWrapper<T> {

    @Override
    public String getChannelName() {
        return "Jackson-ION";
    }


    @Override
    public byte[] serialize() {
        try {

            IonObjectMapper mapper = new IonObjectMapper();
// and then read/write data as usual
            mapper.registerModule(new JavaTimeModule());
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            byte[] encoded = mapper.writeValueAsBytes(this.dataSend);
            stopWatch.stop();
            timeSe = stopWatch.getTotalTimeNanos();
            lengthSource = encoded.length;
            return encoded;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deserialize(byte[] source) {
        try {// 创建ProtobufMapper实例

            IonObjectMapper mapper = new IonObjectMapper();
            mapper.registerModule(new JavaTimeModule());
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            T otherValue = mapper.readValue(source, getMainClazz());
            stopWatch.stop();
            timeDse = stopWatch.getTotalTimeNanos();
            this.resultSe = this.dataSend.equals(otherValue);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!this.resultSe) {
            throw new RuntimeException("反解析结果不一致!!!");
        }
    }

}
